import {
  FC,
  ReactElement,
  useCallback,
  useMemo,
  useRef,
  useState,
} from "react";
import { addTodo } from "../../components/TodoList/actions";
import {
  Button,
  TextInput,
  DateTimePicker,
  BetweenBox,
  ItemCenterBox,
  IDateTime,
} from "../BUI";
import LoadIcon from "../BUI/Icon/LoadIcon";
import { IAction } from "./types";

interface IProps {
  dispatch: React.Dispatch<IAction>;
}

const date = new Date();

const today = {
  year: date.getFullYear(),
  month: date.getMonth() + 1,
  day: date.getDate(),
  hour: date.getHours(),
  minutes: date.getMinutes(),
};

const TodoInput: FC<IProps> = ({ dispatch }): ReactElement => {
  const input = useRef<HTMLInputElement | null>(null);
  const [fetching, setFetching] = useState(false);
  const [todoDate, setTodoDate] = useState<Date>(new Date());

  const handleAddTodo = useCallback(async () => {
    const todoContent = input.current as HTMLInputElement;
    const content = todoContent.value;
    if (content) {
      setFetching(true);
      const todo = { content, reminderTime: todoDate };
      await addTodo(todo)(dispatch);
      todoContent.value = "";
      setFetching(false);
    }
  }, [dispatch, input, todoDate]);

  const selectDate = useCallback((dateTime: IDateTime) => {
    const { year, month, day, hour, minutes } = dateTime;
    const date = `${month} ${day},${year} ${hour}:${minutes}:0`;
    setTodoDate(new Date(date));
  }, []);

  const memoAddTodo = useMemo(
    () => (
      <Button onClick={handleAddTodo}>
        {fetching ? <LoadIcon /> : null}
        addTodo
      </Button>
    ),
    [fetching, handleAddTodo]
  );

  return (
    <BetweenBox item='flex-end' dir='column'>
      <TextInput width='15rem' placeholder='todo' ref={input} />
      <ItemCenterBox>
        时间:
        <DateTimePicker
          defaultDateTime={today}
          onSubmit={selectDate}
          timePicker={true}
          noShadow={true}
          style={{ zIndex: 3 }}
        />
      </ItemCenterBox>
      {memoAddTodo}
    </BetweenBox>
  );
};

export default TodoInput;
